﻿
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using FluentValidation;
using FluentValidation.AspNetCore;
using Cms.Core.Validation.FluentValidations;
using Cms.Core.Validation.IService;
using Cms.Core.Validation.Service;
using System.Linq;
using System.Collections.Generic;

namespace Cms.Core.Validation.FluentValidations
{
   public static class ServiceCollectionExtensions
    {

        /// <summary>
        /// 添加FluentValidation
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IMvcBuilder AddValidators(this IMvcBuilder builder, IServiceCollection services)
        {
            //注入验证结果格式化器
            services.TryAddSingleton<IValidateResultFormatHandler, ValidateResultFormatHandler>();
            services.TryAddScoped<IValidationService, ValidationService>();
            builder.AddFluentValidation(fv =>
            {
                ///去掉其他验证，只使用FluentValidation验证规则
                fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;

                 var validationServices=  services.BuildServiceProvider().GetRequiredService<IEnumerable<IValidationService>>();

                foreach (var validation in validationServices)
                {
                    fv.RegisterValidatorsFromAssemblyContaining(validation.GetType());
                }
                //fv.RegisterValidatorsFromAssemblyContaining<ManagerRoleValidation>
                //var modules = services.BuildServiceProvider().GetService<IModuleCollection>();
                //foreach (var moduleInfo in modules)
                //{
                //    fv.RegisterValidatorsFromAssembly(moduleInfo.AssembliesInfo.Application);
                //}
            });

            ////当一个验证失败时，后续的验证不再执行
            ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;
            return builder;
        }
    }
}
